package Utilities;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Contains methods for writing the voltage data from file and reading in the data
 * @author Shaowei
 *
 */
public class FileServices {

	/**
	 * Write the Hashmap to a file with each timestamp and voltage data
	 * in one line
	 * 
	 * @param voltageData
	 */
	public static void writeToFile(Map<String, Double> voltageData) {
		String data = "";
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(
					new FileWriter(new File("voltages.txt"), true));
			for (Map.Entry<String, Double> entry : voltageData.entrySet()) {
				data = entry.getKey() + " " + entry.getValue();
				bw.write(data);
				bw.newLine();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Read in the whole file
	 * 
	 * @return
	 */
	public static Map<String, Double> readFromFile() {
		Map<String, Double> voltageData = new HashMap<String, Double>();

		try {
			// Open the file that is the first
			// command line parameter
			FileInputStream fstream = new FileInputStream("voltages.txt");
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			// Read File Line By Line
			while ((strLine = br.readLine()) != null) {
				// Print the content on the console
				// System.out.println(strLine);
				String[] temp = strLine.split(" ");
				voltageData.put(temp[0], Double.parseDouble(temp[1]));
			}
			// Close the input stream
			in.close();
		} catch (Exception e) {// Catch exception if any
			System.err.println("[SmartMeter] Error: " + e.getMessage());
		}

		return voltageData;
	}
}
